import { getDB, closeDB } from "@/utils/db";
import { newId } from "@/utils/id";
import { err, ok } from "@/utils/resp";

export async function GET() {
  try {
    const db = await getDB();
    const cfips: Cfip[] = await db.all(
      "SELECT id,name,code,ip FROM cfips ORDER BY id ASC"
    );
    await closeDB();
    return ok(cfips);
  } catch (e) {
    return err(e as Error);
  }
}

export async function POST(req: Request) {
  try {
    const cfip: Cfip = await req.json();
    cfip.id = newId();
    const db = await getDB();
    await db.run(
      "INSERT INTO cfips (id, name, code, ip) VALUES (?, ?, ?, ?)",
      cfip.id!,
      cfip.name,
      cfip.code,
      cfip.ip
    );
    await closeDB();
    return ok(cfip);
  } catch (e) {
    return err(e as Error);
  }
}

export async function PUT(req: Request) {
  try {
    const cfip: Cfip = await req.json();

    if (!cfip.id) {
      throw new Error("请指定ID");
    }

    const db = await getDB();
    const r = await db.run(
      "UPDATE cfips SET name=?, code=?, ip=? WHERE id=?",
      cfip.name,
      cfip.code,
      cfip.ip,
      cfip.id!
    );
    await closeDB();
    return ok({ cfip, aff: r.changes });
  } catch (e) {
    return err(e as Error);
  }
}
